package com.ruoyi.api.daoru;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ImportAddressService {

    @Autowired
    private ImportUtils importUtils;

    public ImportResult validateAndImport(MultipartFile file) {
        return importUtils.importData(file, ImportAddress.class, this::validateAddress, this::batchInsertAddresses);
    }

    // 地址数据校验方法
    private List<String> validateAddress(ImportAddress address, int rowIndex) {
        List<String> errors = new ArrayList<>();

        if (StringUtils.isEmpty(address.getErJi())) {
            errors.add("二级地址不能为空");
        }
        if (StringUtils.isEmpty(address.getYiJi())) {
            errors.add("一级地址不能为空");
        }
        if (!ImportAddress.StatusAddress.isValidCode(address.getSanJi())) {
            errors.add("无效的三级地址状态值");
        }

        return errors.stream()
                .map(msg -> "第" + rowIndex + "行：" + msg)
                .collect(Collectors.toList());
    }

    // 地址数据保存方法
    @Transactional
    public Void batchInsertAddresses(List<ImportAddress> addressList) {
        System.out.println("================执行这个方法了");
        for (ImportAddress importAddress : addressList) {
            System.out.println("地址=======" + importAddress);
        }
        return null;
    }
}
